package com.qs.oauth2.server.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.InMemoryAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;

@Configuration
@EnableAuthorizationServer
public class MyAuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private ClientDetailsService clientDetailsService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private DefaultTokenServices defaultTokenServices;

    @Autowired
    private AuthorizationCodeServices authorizationCodeServices;

    /**
     * 配置客户端详情
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("c1")
                .secret(new BCryptPasswordEncoder().encode("secret")) //客户端访问密码
                .resourceIds("res1","user_res") //资源id集合
                //定义的四种授权模式（refresh_token除外）
                .authorizedGrantTypes("authorization_code", "password", "client_credentials", "implicit", "refresh_token")
                .scopes("all","user_scope") //允许授权范围，可以为空
                .autoApprove(false) //是否自动授权（授权码模式适用）
                .redirectUris("http://www.baidu.com"); //授权后跳转地址（授权码模式适用）
    }

    /**
     * 配置令牌端点安全约束
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                //公开checkToken这个端点（/oauth/check_token 资源服务器调用该端点解析校验令牌）
                .checkTokenAccess("permitAll()")
                //公开tokenKey这个端点（/oauth/token_key 用来提供公有密匙的端点，如果使用JWT令牌的话）
                .tokenKeyAccess("permitAll()")
                .allowFormAuthenticationForClients();  //允许表单认证
    }

    /**
     * 配置授权配置和令牌服务、令牌存储方式
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager)
                .tokenServices(defaultTokenServices)
                .authorizationCodeServices(authorizationCodeServices)
                .allowedTokenEndpointRequestMethods(HttpMethod.POST, HttpMethod.GET);
    }

    //暂时将令牌存储在内存中
    @Bean
    public TokenStore tokenStore() {
        return new InMemoryTokenStore();
    }

    //设置令牌服务：包括令牌存储方式、令牌有效期等
    @Bean
    public DefaultTokenServices defaultTokenServices() {
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setClientDetailsService(clientDetailsService);
        defaultTokenServices.setTokenStore(tokenStore);
        defaultTokenServices.setSupportRefreshToken(true);  //是否支持刷新token
        defaultTokenServices.setAccessTokenValiditySeconds(300);  //设置令牌有效期5分钟
        defaultTokenServices.setRefreshTokenValiditySeconds(600);  //设置刷新令牌有效期10分钟
        return defaultTokenServices;
    }

    //设置授权码模式的授权码如何存取，暂时采用内存方式
    @Bean
    public AuthorizationCodeServices authorizationCodeServices() {
        return new InMemoryAuthorizationCodeServices();
    }
}
